<?php
namespace Admin\Controller;
use Think\Controller;
class RbacController extends CommonController {

	public function Index()
	{
	$User = M("User"); // 实例化User对象
    $count      = $User->where("account<>'admin'")->count();// 查询满足要求的总记录数
    $Page       = new \Think\Page($count,$num=5);// 实例化分页类 传入总记录数和每页显示的记录数(25)
    $show       = $Page->show();// 分页显示输出// 进行分页数据查询 注意limit方法的参数要使用Page类的属性
    $ulist = $User->where("account<>'admin'")->order("sort")->limit($Page->firstRow.','.$Page->listRows)->select();        
		$remark 	= M();
		//将管理员角色添加到数组中
		foreach($ulist as $k=>$vo){
			
			$sql   		= "select name from tr_role where id in(
								    select role_id from tr_role_user where user_id={$vo['id']})";
			$rname 		= $remark->query($sql);
			$rstr 		= "";
			foreach($rname as $v){
				$rstr  .= $v['name'].",";
			}
			$rstr	    = rtrim($rstr,",");
			$ulist[$k]['jiaose'] = $rstr;
		}
		$this->assign('ulist',$ulist);
   		 $this->assign('page',$show);// 赋值分页输出  
		$this->display();
	}
	//------------- 删除管理员帐号 -------------------//
	public function del(){
		$id = isset($_POST['id'])?$_POST['id']:'';
		if (strpos($id,',')>-1) {
			$id = rtrim($id,',');
		}
		$User 	   = M("User");
		$role_user = M("Role_user");
		$rdel	   = $role_user->where("user_id='$id'")->delete();
		$result    = $User->delete($id);
		if ($result !== false) {
			$data['message'] = "<span style='color:green;'>您删除 ".$result." 条数据成功</span>";
			$data['status']  = 1; 
		}else{
			$data['message'] = "<span style='color:red;'>您删除条数据失败</span>";
			$data['status']  = 0; 
		}
		echo json_encode($data); 
	}
	//------------ 管理员帐号列表排序 ------------------------//
	public function sort(){
		//排序信息 取整
		$User 	= M("user");
		foreach ($_POST['sort'] as $key=>$vo){ //循环排序
			$data['sort'] = $vo;
			$result	= $User->where("id=".$_POST['id'][$key])->save($data);
		}
	}
	//----------- 添加管理员信息 ---------------------//
	public function insert(){
		
		if($_POST['action'] == "add"){
			if ($_POST['account'] == ''||$_POST['password'] == "") {
				$this->error("数据不能为空");
				exit;
			}
			$User = D("User");
			$data['account'] = $_POST['username'];
			$find = $User->where($data)->find();
			if(!empty($find)){
				$this->error("帐号已存在");
				exit;
				
			}
			$_POST['password'] = md5($_POST['password']);
			if($User->create()){
				$add = $User->add();
				$role_user = M("Role_user");
				$rdata['role_id'] = $_POST['role_id'];
				$rdata['user_id'] = $add; //将新创建的帐号id 放入
				$radd = $role_user->add($rdata);
				if ($radd === false) {
					$this->error("角色分配失败");
					exit();
				}
				if ($add !== false) {
					$this->success('创建帐号id='.$add.'成功');
				}else{
					$this->error("创建帐号失败");
				}
			}else{
				$this->error($User->getError());
			}
			exit();
		}
		$Role  = M("Role"); 
		$rlist = $Role->select();
		$this->assign('rlist',$rlist);
		$this->display();
	}
	//------------ 修改管理员信息 --------------------//
	public function rbedit(){
		$User  = M("User");
		if ($_POST['action'] == "edit") {
			if (empty($_POST['password'])) {
				unset($_POST['password']);
			}else{
				$_POST['password'] = md5($_POST['password']);
			}
			if($User->create()){
				$role_id 	= isset($_POST['role_id'])?$_POST['role_id']:'';
				$role_user  = M("Role_user");
				//删除 uid在 role_user 表中数据 后在添加
				$rdel	    = $role_user->where("user_id={$_POST['uid']}")->delete();
				if ($rdel === false) {
					$this->error("角色节点更新失败");
					exit();
				}
				foreach($role_id as $v){
					$rdata['role_id'] = $v;
					$rdata['user_id'] = $_POST['uid']; //将新创建的帐号id 放入
					$radd 			  = $role_user->add($rdata);
					if ($radd === false) {
						$this->error("角色分配失败");
						exit();
					}
				}
				if($result !== false){
					$this->success('更新帐号数据成功');
				}else{
					$this->error("更新帐号数据失败","rbedit/id/{$_POST['uid']}");
				}
				
			}else{
				$this->error($User->getError());
			}
			exit();
		}
		
		$ulist	= $User->where("id={$_GET['id']}")->find();
		//查询当前编辑管理员的所有角色
		$ru 			 = M();
		$sql 			 = "select role_id from tr_role_user where user_id={$ulist['id']}";
		$role			 = $ru->query($sql);
		$arr 			 = array();
		foreach($role as $v){
			$arr[] = $v['role_id'];
		}
		$ulist['roleid']= $arr;
		$Role  			 = M("Role");
		$rlist 			 = $Role->select();
		$this->assign('rlist',$rlist);
		$this->assign('ulist',$ulist);
		$this->display();
	}
		//------------ 角色分组列表显示 ---------------//
	public function role($num=5)
    {		$User = M("Role"); // 实例化User对象
    	$count      = $User->where('status=1')->count();// 查询满足要求的总记录数
    $Page       = new \Think\Page($count,$num);// 实例化分页类 传入总记录数和每页显示的记录数(25)
    $show       = $Page->show();// 分页显示输出// 进行分页数据查询 注意limit方法的参数要使用Page类的属性
    $list = $User->where('status=1')->order('create_time')->limit($Page->firstRow.','.$Page->listRows)->select();
    $Rek=M();
		// 循环条件 查处所有角色下的所有 子节点 使用 逗号连接 并放入输出数组中 //
		foreach ($list as $k=>$v){
			$sql 		= "select remark,status,title from tr_node where id in(
						select node_id from tr_access where role_id in (
						select id from tr_role where id={$v['id']}
					))";
			$rarr 		= $Rek->query($sql);  
			   
			foreach ($rarr as $v2){
				
				$remark[] = $v2['title'];
			}
			$list[$k]['node'] .= implode(",",$remark);

			unset($remark);//将数据清空
		}

		    $this->assign('list',$list);// 赋值数据集
    		$this->assign('page',$show);// 赋值分页输出     
		$this->display();

	}
	//--------- 角色创建 并分配权限 -----------// 
	public function addrole(){
		
		$Node 	= M("Node");
		$Role 	= D("Role");	   
		$action = isset($_POST['action'])?$_POST['action']:'';
		if ($action == "add") {
			//检测角色名是否重复
			$rel = $Role->where("name='{$_POST['name']}'")->count();
			if ($rel>0) {
				$this->error("角色已存在");
				exit();
			}			
			//添加角色
			if($Role->create()){
				$result = $Role->add();//成功返回自增长的主键
				if($result !== false){
					//-------- 添加对应权限 -----------//
					$Access = M("Access");
					$narr = $_POST['node'];
					foreach ($narr as $v){
						$level			 = $Node->field('level')->where("id=$v")->find(); //查询节点等级
						$data['level']	 = $level['level'];
						$data['role_id'] = $result; //将新创建的角色id放入数组
						$data['node_id'] = $v;		//节点id
						$data['status']  = 1; 		//状态打开
						if($Access->add($data) === false){
							$this->error("权限添加失败");
							exit;
						}
					}
					$this->success("创建成功","role");
				}else{
					$this->error("创建失败");
					exit();
				}
			}else{
				$this->error($Role->getError());
			}
			exit();
		}
		//权限 节点
		$nlist	 = $Node->where('status>0')->select();   
		$rlist 	 = $Role->field("id,name")->select();  
		$nlist   = nAllselect($nlist);
		$this->assign("nlist",$nlist);
		$this->assign("rlist",$rlist);
		$this->display();
	}
		//------------ 删除 角色表数据 ---------------//
	public function delrole(){
		$id = isset($_POST['id'])?$_POST['id']:'';
		if (strpos($id,',')>-1) {
			$id = rtrim($id,',');
		}
		$Role	 = M("Role");
		$Access	 = M("Access");
		//------- 先删除当前角色权限 -------//
		$delres = $Access->where("role_id in($id)")->delete();
		if ($delres === false) {
			echo "<span style='color:red;'>删除$delres条权限失败</span>";
			exit;
		}		
		$result	 = $Role->delete($id);
		$result  = $Role->delete($id);
		if ($result !== false) {
			echo "<span style='color:green;'>您删除数据成功</span>";
		}else{
			echo  "<span style='color:red;'>您删除条数据失败</span>";
		}
	}
	//---------- 编辑 角色分组 可修改权限 -----------//
	public function editrole(){
		
		$action = isset($_POST['action'])?$_POST['action']:'';
		$Node 	= M("Node");
		$Role 	= D("Role");
		if ($action == "eidt") {
			$id		= isset($_POST['id'])?$_POST['id']:'';
			//编辑角色分组
			if($Role->create()){
				$result = $Role->where("id=$id")->save();
				if($result !== false){
					$Access = M("Access");
					//------- 先删除当前角色权限 -------//
					$delres = $Access->where("role_id=$id")->delete();
					if ($delres === false) {
						$this->error("删除权限失败");
						exit;
					}
					//-------- 添加对应权限 -----------//
					$narr = $_POST['node'];
					foreach ($narr as $v){
						$level			 = $Node->field('level')->where("id=$v")->find(); //查询节点等级
						$data['level']	 = $level['level'];
						$data['role_id'] = $id; //将新创建的角色id放入数组
						$data['node_id'] = $v;		//节点id
						$data['status']  = 1; 		//默认状态打开
						if($Access->add($data) === false){
							$this->error("权限更改失败");
							exit;
						}
					}
					$this->success("角色更新成功");
				}else{
					$this->error("角色更新失败");
					exit();
				}
			}else{
				$this->error($Role->getError());
			}
			exit();
		}
		
		$id 	 = isset($_GET['id'])?$_GET['id'] :'';
		//权限 节点
		$nlist	 = $Node->where('status<>0')->select();
		$rlist 	 = $Role->field("id,name")->select();
		$Rone 	 = $Role->where("id=$id")->find();		//编辑前显示
		$Rek	 = M();		//直接使用$Role 模型对象也可以 但考虑性能问题 使用空模型
		$remark	 = array();
		// 循环条件 查处所有角色下的所有 子节点 使用 逗号连接 并放入输出数组中 //
		$sql 	 = "select node_id from tr_access where role_id in (
						select id from tr_role where id={$id})";
		$rarr 	 = $Rek->query($sql);
		foreach ($rarr as $v2){
			$remark[] = $v2['node_id'];
		}
		$Rone['node'] = $remark;
		// --- 调整 数组格式 显示出层数感 --- //
		$nlist  = nAllselect($nlist);
		$this->assign("Rone",$Rone);
		$this->assign("nlist",$nlist);
		$this->assign("rlist",$rlist);
		$this->display();
	}
	//------------ 管理权限节点展示-----------------//
	public function jurisdiction(){
	$keyword 	   	= isset($_GET['keyword'])?$_GET['keyword']:'';
	$map['title']	= array("like","%$keyword%");
	$Node 		= M("Node"); // 实例化User对象
    $count      = $Node->where($map)->count();// 查询满足要求的总记录数
    $Page       = new \Think\Page($count,$num=10);// 实例化分页类 传入总记录数和每页显示的记录数(25)
    $show       = $Page->show();// 分页显示输出// 进行分页数据查询 注意limit方法的参数要使用Page类的属性
    $nlist = $Node->where($map)->order("sort")->limit($Page->firstRow.','.$Page->listRows)->select();  
		foreach ($nlist as $k=>$v){
			
			$pname  = $Node->field("title")->where("id={$v['pid']}")->find();
			if(empty($pname)){//为空则自身没有父节点
				$nlist[$k]['pname'] = "无父节点";
			}else{
				$nlist[$k]['pname'] = $pname['title'];
			}
		}		
		$this->assign("showpage",$show);
		$this->assign("nlist",$nlist);
		$this->display();
	}
	
	//------------ 管理权限节点添加 ------------//
	public function jurisdictionadd(){
		
		$Node 		= M("Node");
		$action 	= isset($_POST['action'])?$_POST['action']:'';
		if ($action == "add") {
			//创新数据对象 默认接受$_POST数组
			if($Node->create()){
				$result = $Node->add();
				if ($result !== false) {
					$this->success("添加节点成功");
				}else{
					$this->error("添加节点失败");
					exit();
				}
			}else{
				$this->error($Node->getError());
			}
			exit();
		}		
		$nlist 		= $Node->where('level<>3')->select(); //底层操作不显示
		// --- 将数组按等级重新排列 --- //
		$arr 		= array();
		nselect($nlist,$arr);
		$this->assign("nlist",$arr);
		$this->display();
	}
	//------------ 管理权限节点编辑 ------------//
	public function jurisdictionedit(){
		
		$Node 		= M("Node");
		$action 	= isset($_POST['action'])?$_POST['action']:'';
		if ($action == "edit") {
			//编辑数据对象 默认接受$_POST数组
			if($Node->create()){
				$result = $Node->where('id='.$_POST['id'])->save();
				if ($result !== false) {
					$this->success("编辑成功","jurisdiction/p/{$_POST['p']}"); //失败提示
				}else{
					$this->error("编辑失败"); //失败提示
				}
			}else{
				$this->error($Node->getError()); //失败提示
			}
			exit();
		}		
		$id			= isset($_GET['id'])?$_GET['id']:'';
		$p			= isset($_GET['p'])?$_GET['p']:'';
		$nodearr 	= $Node->where("id={$id}")->find(); 
		$nlist 		= $Node->where('level<>3')->select(); //底层操作不显示
		$this->assign("nodearr",$nodearr);
		// --- 将数组按等级重新排列 --- //
		$arr 		= array();
		nselect($nlist,$arr);
		$this->assign("nlist",$arr);
		$this->assign("p",$p);
		$this->display();
	}
	
	//--------- 管理权限节点删除 ------------//
	public function jurisdictiondel(){
		$id = isset($_POST['id'])?$_POST['id']:'';
		$Node	= M("Node");
		$nlist	= $Node->select();
		$str 	= '';
		if (strpos($id,',')>-1) {
			$id 	= rtrim($id,',');
			$idarr  = explode(",",$id);
			foreach ($idarr as $v){
				nodeselect($nlist,$str,$v);
			}
		}else{
			nodeselect($nlist,$str,$id);
		}
	
		$ids = $str.$id;
		$result = $Node->delete($id);
		if ($result !== false) {
			$data['message'] = "<span style='color:green;'>您删除 ".$result." 条数据成功</span>";
			$data['status']  = 1;
		}else{
			$data['message'] = "<span style='color:red;'>您删除条数据失败</span>";
			$data['status']  = 0;
		}
		echo json_encode($data);
	}
	//--------修改管理权限节点状态-----------//
	public function status(){
		$n  			= isset($_POST['n'])?$_POST['n']:'';
		$id 			= isset($_POST['id'])?$_POST['id']:'';
		$Node 			= M("Node");
		$data['status'] = $n; 
		$result			= $Node->where("id={$id}")->save($data);		
	}
	
}